package com.itheima.goodsconsumer.api;

import com.itheima.goodsconsumer.VO.ResultVO;
import com.itheima.goodsconsumer.constant.ResultEnum;
import com.itheima.goodsconsumer.model.User;
import com.itheima.goodsconsumer.service.UserService;
import com.itheima.goodsconsumer.util.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.itheima.goodsconsumer.util.ResultVOUtil.success;

@RestController
@RequestMapping("/api/admin")
public class UserAPI {
    @Autowired
    UserService userService;

     // 用户登录
    @GetMapping(value = "/login")
    public ResultVO login(HttpServletRequest request,String uname, String upassword) {
        if (userService.login(uname) != null) {
            User user = userService.login(uname);
            if (user.getUpassword().equals(upassword)){
                HttpSession session = request.getSession(true);
                session.setAttribute("user", userService.login(uname));  //将登陆者信息存入session
              //return "redirect:http://localhost:8896/goods/getAll?uaccount="+userService.login(uname).getUaccount()+"&upasswoed="+userService.login(uname).getUpassword();
                System.out.println("登录成功");
                return ResultVOUtil.success(user);
            }
        }
       // request.setAttribute("mag","账号密码错误");
        System.out.println("登录失败，重新登录");
        return ResultVOUtil.error(ResultEnum.LOGIN_FAIL);
    }
    //用户注册
    @GetMapping(value = "/register")
    public ResultVO register(HttpServletRequest request, String uname,String upassword,String usex) {
       if(userService.register(upassword, uname, usex)>0){
           System.out.print("注册成功");
           return success();
       }
        System.out.print("注册失败");
        return ResultVOUtil.error(ResultEnum.LOGIN_FAIL);
    }
}